<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者名称" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生名称" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医院名称" prop="hospitalName">
        <el-input
          v-model="queryParams.hospitalName"
          placeholder="请输入医院名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入科室名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="取消原因" prop="cancelReason">
        <el-input
          v-model="queryParams.cancelReason"
          placeholder="请输入取消原因"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增等按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:appointments:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:appointments:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:appointments:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:appointments:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 显示窗口 -->
    <el-table v-loading="loading" :data="appointmentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者名称" align="center" prop="patientName" />
      <el-table-column label="身份证号" align="center" prop="idCard" />
      <el-table-column label="医生名称" align="center" prop="doctorName" />
      <el-table-column label="科室名称" align="center" prop="deptName" />
      <el-table-column label="就诊日期" align="center" prop="date" />
      <el-table-column label="就诊时段" align="center" prop="timeSlot" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:appointments:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:appointments:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- // 分页逻辑 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者名称" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者名称" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>

        <!-- 以下三层，医院决定科室，科室决定医生，必须先选择，医院，然后科室的下拉框内容通过医院的科室
         医生和科室也是同理     -->
         <!-- 其实没必要医院，因为这是管理员端，是病人来到我们医院，我才录入，所以医院是定的，只有一个医院，
          当然如果是网上预约，且医院连锁当我没说，但是这个输入预约信息的功能应该不可能给用户权限 -->


        <el-form-item label="医院名称" prop="hospitalName">
          <el-select
            v-model="form.hospitalName"
            @change="handleHospitalChange"
            placeholder="选择你的医院">
            <el-option
              v-for="hospital in hospitalsList"
              :key="hospital.hospitalId"
              :label="hospital.hospitalName"
              :value="hospital.hospitalName"
             />
          </el-select>
        </el-form-item>

        <el-form-item label="科室名称" prop="deptName">
          <el-select
            v-model="form.deptName"
            @change="handleDeptChange"
            placeholder="请选择科室"
          >
            <el-option
              v-for="dept in filteredDeptList "
              :key="dept.label"
              :label="dept.label"
              :value="dept.label"
            />
          </el-select>
        </el-form-item>

        <!-- 这里可以有两种预约方式，一种是先选择医生之后根据医生的时间段来就医 -->
         <!-- 二是先选择时间段，然后看该时间段有时间的医生 -->
          <!-- 目前先显示第一种 -->

        <el-form-item label="医生姓名" prop="doctorName">
            <el-select v-model="form.doctorName"
            :placeholder="form.deptName ? '请选择医生' : '请先填写科室'"
            :disabled="!form.deptName"
            @change="handleDoctorChange"
            >
              <el-option
                v-for="doctor in filteredDoctorList"
                :key="doctor.label"
                :label="doctor.label"
                :value="doctor.label"
              />
            </el-select>
          </el-form-item>

          <!-- 似乎预约之后，后端数据库修改的时候，医生的号源也要 - 1 -->

          <!-- 就诊日期和时间段 通过医生的排班来决定 -->


        <el-form-item label="就诊日期" prop="date">
            <el-select v-model="form.date"
            :placeholder="form.date ? '请选择日期' : '请先选择医生'"
            :disabled="!form.doctorName"
            @change="handleDateChange"
            >
              <el-option
                v-for="schedule in schedulesList"
                :key="schedule.date"
                :label="schedule.date"
                :value="schedule.date"
              />
            </el-select>
          </el-form-item>


        <!-- 就诊时段必选 -->
        <el-form-item label="就诊时段" prop="timeSlot">
          <el-input v-model="form.timeSlot" placeholder="请输入就诊时段" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppointments, getAppointments, delAppointments, addAppointments, updateAppointments } from "@/api/system//hospitals/appointments"
import { listDoctors } from "@/api/system/hospitals/doctors"
import {listDepartments} from "@/api/system/hospitals/departments"
import {listSchedules} from "@/api/system/hospitals/schedules"
import {getDeptName, listHospitals} from "@/api/system/hospitals/hospitals"

export default {
  name: "Appointment",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预约订单表格数据
      appointmentsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        idCard: null,
        doctorName: null,
        hospitalName: null,
        deptName: null,
        timeSlot: null,
        cancelReason: null,
        date: null,
      },
      doctorList: [],
      deptList: [],
      filteredDoctorList: [],
      schedulesList: [],
      doctorLoading: false,
      deptLoading: false,
      scheduleLoading: false,
      hospitalsList: [],
      hospitalLoading: false,
      filteredDeptList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        timeSlot: [
          { required: true, message: "就诊时段不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "就诊时段不能为空", trigger: "blur" }
        ],
        patientName: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" }
        ],
        hospitalName: [
          { required: true, message: "医院名称不能为空", trigger: "blur" }
        ],
        doctorName: [
          { required: true, message: "医生姓名不能为空", trigger: "blur" }
        ],
        date: [
          { required: true, message: "就诊日期不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  mounted(){
    this.fetchDoctors();
    this.fetchDepts();
    this.fetchHospitalName();
  },
  methods: {

    // 获取医院名称
    async fetchHospitalName(){
      this.hospitalLoading = true;
      try{
        console.log("获取医院名称")
        const response = await listHospitals({});
        console.log("医院名称:", response.rows);
        this.hospitalsList = response.rows
          .filter(item => item.hospitalName) // 过滤 doctorName 为 null 的项
          .map(item => ({
            hospitalId: item.hospitalId,
            hospitalName: item.hospitalName
          }))
        if (!this.hospitalsList.length) {
          this.$message.warning('暂无医院数据');
        }
      } catch (error) {
        this.$message.error('获取医院数据失败');
        console.error('Error fetching hospitals:', error); // 打印详细错误
      } finally {
        this.hospitalLoading = false;
      }
    },

    // 选择医院后筛选出对应的科室逻辑
    handleHospitalChange(hospitalName) {
        // 清空已选的科室
      this.form.deptName = '';

        // 1. 根据 hospitalName 找到对应的 hospitalId
        const selectedHospital = this.hospitalsList.find(
          hospital => hospital.hospitalName === hospitalName
        );

        if (!selectedHospital) {
          console.warn('未找到匹配的医院:', hospitalName);
          this.filteredDeptList = []; // 如果没有匹配的医院，清空科室列表
          return;
        }

        const hospitalId = selectedHospital.hospitalId;

      // 根据医院名称过滤科室列表
      this.filteredDeptList = this.deptList.filter(
        dept => dept.hospitalId === hospitalId
      );
    },


    // 获取医生信息
    async fetchDoctors() {
      try {
        this.doctorLoading = true;
        console.log("Fetching doctors...");
        const response = await listDoctors({});
        console.log("医生数据：", response.rows); // 改进日志输出
        this.doctorList = response.rows
          .filter(item => item.doctorName) // 过滤 doctorName 为 null 的项
          .map(item => ({
            value: item.doctorId,
            label: item.doctorName,
            deptName: item.deptName // 保留科室信息
          }));
        if (!this.doctorList.length) {
          this.$message.warning('暂无医生数据');
        }
      } catch (error) {
        this.$message.error('获取医生数据失败');
        console.error('Error fetching doctors:', error); // 打印详细错误
      } finally {
        this.doctorLoading = false;
      }
    },


    // 医生下拉框选择后触发的逻辑
    handleDoctorChange(value) {
        const selectedDoctor = this.doctorList.find(doctor => doctor.label === value);
        if (selectedDoctor) {
          this.form.doctorName = selectedDoctor.label;
          this.fetchSchedules(selectedDoctor.label); // 加载该医生的排班
        }
    },

    // 科室下拉框选择后触发的逻辑
    handleDeptChange(deptName) {
        // 清空已选的医生
      this.form.doctorName = '';

      // 根据科室名称过滤医生列表
      this.filteredDoctorList = this.doctorList.filter(
        doctor => doctor.deptName === deptName
      );
    },

    // 获取科室信息
    async fetchDepts() {
      try {
        this.deptLoading = true;
        console.log("Fetching 科室...");
        const response = await listDepartments({});
        console.log("科室：", response.rows); // 改进日志输出
        this.deptList = response.rows
          .filter(item => item.deptName) // 过滤 doctorName 为 null 的项
          .map(item => ({
            value: item.deptId,
            label: item.deptName,
            hospitalId: item.hospitalId
          }));
        if (!this.deptList.length) {
          this.$message.warning('暂无科室数据');
        }
      } catch (error) {
        this.$message.error('获取科室数据失败');
        console.error('Error fetching department:', error); // 打印详细错误
      } finally {
        this.deptLoading = false;
      }
    },

    // 获取预约安排信息
    async fetchSchedules(doctorName) {
      try {
        this.scheduleLoading = true;
        console.log("Fetching 时间安排...");
        const response = await listSchedules({});
        console.log("预约日期：", response.rows); // 改进日志输出
        this.schedulesList = response.rows
          .filter(item => item.doctorName === doctorName); // 过滤 doctorName 为 null 的项

        if (!this.schedulesList.length) {
          this.$message.warning('暂无预约日期数据');
        }
      } catch (error) {
        this.$message.error('获取预约日期数据失败');
        console.error('Error fetching date:', error); // 打印详细错误
      } finally {
        this.scheduleLoading = false;
      }
    },


    // 预约时间选择后的逻辑
    handleDateChange(value) {
      const selectedDate = this.schedulesList.find(schedule => schedule.date === value);
      // this.form.date = selectedDate ? selectedDate.date : ''; // 可选，更新 date 显示
      if (selectedDoctor) {
        // 更新表单中的医生姓名
        this.form.doctorName = selectedDoctor.doctorName;

        // 清空之前选择的日期和时间段
        this.form.date = '';

        // 调用 fetchSchedules 并传入医生姓名
        this.fetchSchedules(selectedDoctor.doctorName);
      }
    },


    /** 查询预约订单列表 */
    getList() {
      this.loading = true
      listAppointments(this.queryParams).then(response => {
        this.appointmentsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        appointmentId: null,
        patientName: null,
        idCard: null,
        doctorName: null,
        hospitalName: null,
        deptName: null,
        timeSlot: null,
        cancelReason: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.appointmentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加预约订单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const appointmentId = row.appointmentId || this.ids
      getAppointments(appointmentId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改预约订单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.appointmentId != null) {
            updateAppointments(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAppointments(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const appointmentIds = row.appointmentId || this.ids
      this.$modal.confirm('是否确认删除预约订单编号为"' + appointmentIds + '"的数据项？').then(function() {
        return delAppointments(appointmentIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/appointments/export', {
        ...this.queryParams
      }, `appointments_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
